<template>
  <a-card class="content" :bordered="false">
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="48">
          <a-col :md="8" :sm="24">
            <a-form-item label="团购ID">
              <a-input v-model="queryParam.id" placeholder=""/>
            </a-form-item>
          </a-col>
          <a-col :md="!advanced && 8 || 24" :sm="24">
            <span class="table-page-search-submitButtons" :style="advanced && { float: 'right', overflow: 'hidden' } || {} ">
              <a-button type="primary" @click="query(queryParam.id)">查询</a-button>
              <a-button style="margin-left: 8px" @click="reset">重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <div class="table-operator">
      <a-button type="primary" icon="plus" @click="showModal">新建</a-button>
      <!-- 模态框     -->
      <a-modal v-model="visible" title="创建团购商品" onOk="handleOk" width="70%"
      style="top:30px;height:100%;">
          <!-- 按钮 -->
          <template slot="footer">
            <a-button key="back" @click="handleCancel" style="margin-left: 8px">取消</a-button>
            <a-button key="submit" @click="handleOk" type="primary">确定</a-button>
          </template>
          <!-- 模态框表单 -->
          <!-- 商品属性表单 -->
          <div class="commodityProperty">
            <h1>商品属性（Spu）</h1>
            <a-form :form="form">
              <a-form-item
              label="团购商品"
              :labelCol="{lg: {span: 6}, sm: {span: 6}}"
              :wrapperCol="{lg: {span: 15}, sm: {span: 15} }">
                <el-cascader
                v-model="value"
                :options="groupCommodity"
                @change="groupProduct"></el-cascader>
              </a-form-item>
              <a-form-item
              label="团购时间"
              :labelCol="{lg: {span: 6}, sm: {span: 6}}"
              :wrapperCol="{lg: {span: 15}, sm: {span: 15} }">
                <div>
                  <a-range-picker :value="createValue" @change="groupTime" />
                </div>
              </a-form-item>
              <a-form-item
              label="团购基础人数"
              :labelCol="{lg: {span: 6}, sm: {span: 6}}">
                <div>
                  <a-input-number id="inputNumber" :min="1" :max="10" v-model="valueRS" @change="groupPeople" />
                </div>
              </a-form-item>
              <a-form-item
              label="活动结束时人数没有达到基础人数"
              :labelCol="{lg: {span: 6}, sm: {span: 6},}">
                <div>
                  <a-radio-group defaultValue="1" buttonStyle="solid" @change="judgeShipments">
                    <a-radio-button value="1">自动退款，我不发货</a-radio-button>
                    <a-radio-button value="0">不退款，我要发货</a-radio-button>
                  </a-radio-group>
                </div>
              </a-form-item>
            </a-form>
          </div>
          <!-- 商品类型表单-->
          <div class="commodityType">
            <h1>商品类型（Sku）</h1>
            <a-table :columns="SkuType" :dataSource="SkuTypeDetails" rowKey="id">
              <span slot="action" slot-scope="text,record">
                <a href="javascript:;" v-if="record.id" @click="update(record)">更新</a>
              </span>
              <span slot="price" slot-scope="price">{{price}}</span>
              <span slot="vipPrice" slot-scope="vipPrice">{{vipPrice}}</span>
            </a-table>
          </div>
          <!-- 更新模态框 -->
          <a-modal title="更新团购价格" v-model="visibleUpdate" @ok="handleOkUpdate">
            <a-row>
              <a-col :span="20">
                <a-form-item
                label="团购价格"
                :labelCol="{lg: {span: 10}, sm: {span: 10}}">
                  <div>
                    <a-input-number :min="1" v-model="changePrice"/>
                    <!-- {{databox2}} -->元
                  </div>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="20">
                <a-form-item
                label="现价"
                :labelCol="{lg: {span: 10}, sm: {span: 10}}">
                  <div>{{SkuTypeDetails[0].vipPrice/100}}元</div>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="20">
                <a-form-item
                label="Sku类型名"
                :labelCol="{lg: {span: 10}, sm: {span: 10}}">
                  <div>{{SkuTypeDetails[0].title}}</div>
                </a-form-item>
              </a-col>
            </a-row>
          </a-modal>
      </a-modal>
    </div>
    <!-- 表格 -->
    <a-table :columns="groupBuyingColumns" :dataSource="data" class="components-table-demo-nested" :pagination="pagination"
    :loading="table" rowKey="id">
    <img  style="width:50px;height:50px" slot="img" slot-scope="img" :src="img" />
    <span slot="status" slot-scope="status">
      <a-tag color="blue" v-if="status === undefined"></a-tag>
      <a-tag color="blue" v-if="status === 1">激活</a-tag>
      <a-tag color="blue" v-if="status === 0">冻结</a-tag>
    </span>
    <span slot="action" slot-scope="action, record">
      <a-button type="danger"
        class="table-danger flyray-btn"
          @click="showDeleteConfirm(record)" >删除</a-button>

    </span>
    <span slot="gmtStart" slot-scope="gmtStart">{{gmtStart | formDate}}</span>
    <span slot="gmtEnd" slot-scope="gmtEnd">{{gmtEnd | formDate}}</span>
      <a-table
        slot="expandedRowRender"
        slot-scope="record"
        rowKey="id"
        :columns="SkuDetails"
        :dataSource="record.groupShopSkuDTOList"
        :pagination="false"
      >
      <span slot="skuGroupShopPrice" slot-scope="skuGroupShopPrice">{{skuGroupShopPrice | filterPrice}}</span>
      <span slot="originalPrice" slot-scope="originalPrice">{{originalPrice | filterPrice}}</span>
      <span slot="price" slot-scope="price">{{price | filterPrice}}</span>
      <span slot="vipPrice" slot-scope="vipPrice">{{vipPrice | filterPrice}}</span>
      </a-table>
    </a-table>
  </a-card>

</template>

<script>
import { getRoleList } from '@/api/manage'
import { getList, addGroupShopSpu } from '@/api/mall/groupBuying'
import { getSpuBigTree, detail, deleteGoods } from '@/api/mall/goods'

import { groupBuyingColumns, SkuDetails, SkuType } from '@/const/crud/mall/groupBuying.config'

// 图片上传
function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}


export default {
  name:'groupBuying',
  components: {
  },
  data () {
    return {
      SkuType, //商品类型
      valueRS:1,
      changePrice:0,//更新价格
      editId:null,//更新id
      // 团购商品
      groupCommodity: [],
      imageUrl: '',
      // 表格数据引入
      data: [],
      SkuTypeDetails:[
        {id:'',title:'',vipPrice:null,price:null}
      ],
      createValue:[],//时间日期控件
      table:false,
      pagination: {},
      groupBuyingColumns,
      SkuDetails, //商品展开详情
      // 高级搜索 展开关闭
      advanced: false,
      // 模态框状态
      loading: false,
      visible: false,
      //更新模态框
      visibleUpdate: false,
      // 表单数据
      value: 1,
      form: this.$form.createForm(this),
      // 查询参数
      queryParam: {
        id:null,   // 团购id
      },
      parameter:{
        pageNo:1,  //第一页数据
        pageSize:10,  // 五条
        id:null,
        status: null,
        spuId:null
      },
      // 团购商品
      groupSh:null,
      // 添加数据
      addData:{
        'gmtStart':null,
        'gmtEnd':null,
        'minimumNumber':1,
        'spuId': null,
        'automaticRefund':1,
        'groupShopSkuList':''
      },

    }
  },
  // 计算属性
  computed: {
    // 价格
    Price(){
      return this.SkuTypeDetails[0].price
    },
  },

  filters: {
    // 过滤价格
    filterPrice(price){
      return price
    },
    statusFilter (type) {
      return statusMap[type].text
    },
    statusTypeFilter (type) {
      return statusMap[type].status
    },
  },
  created () {
    this.query();
    this.CommodityTrees();
    getRoleList({ t: new Date() })
  },
  methods: {
    deleteGroupGoods(id) {
      this.parameter.id = id
      deleteGoods(Object.assign(this.parameter)).then(res => {
        console.log(res)
        this.query() //查询
        // console.log(res)
      })
    },
    showDeleteConfirm(val) {
      //var _this = this
      var that = this
      this.$confirm({
        title: `确定删除------${val.id}-------吗？`,
        // content: _this.titl,
        okText: 'Yes',
        okType: 'danger',
        cancelText: 'No',
        onOk() {
          //删除调用
          console.log(val);
          that.parameter.id=val.id;
          console.log(that.parameter.id)
          that.deleteGroupGoods(val.id);
          that.$message.success('您已成功删除');

        },
        onCancel() {
          // console.log('Cancel');
        }
      })
    },

    // update更新模态框
    update(val) {
      this.editId = val.id;
      this.changePrice = val.originalPrice;
      this.visibleUpdate = true;
    },
    handleOkUpdate(e) {
      let that = this;
      that.SkuTypeDetails.forEach(function(ele,index,arr){
          if(ele.id == that.editId){
            ele.vipPrice = that.changePrice;
          }
      })
      this.visibleUpdate = false;
    },

    // 判断是否发货
    judgeShipments(e){
      // console.log(e.target.value)
      this.addData.automaticRefund=e.target.value;
    },
    // 请求skuDetial数据
    skuDetial(){
      detail(Object.assign(this.parameter)).then(res => {
      //  console.log(res)
          let obj={};
          let arr=[];
          // console.log(res)
          this.SkuTypeDetails = res.data.skuList;
          this.addData.spuId=res.data.skuList[0].spuId;
          obj["skuId"]=res.data.skuList[0].id;
          obj["skuGroupShopPrice"]=res.data.skuList[0].price;
          arr.push(obj);
          this.addData['groupShopSkuList']=JSON.stringify(arr);
      })
    },
    // 团购基础人数
    groupPeople(value) {
      // console.log(value)
      this.addData.minimumNumber=value;
    },
    // 团购时间
    groupTime(date, dateString) {
      // console.log(date, dateString);
      this.createValue = date;
      this.addData.gmtStart=date[0]._d.getTime();
      this.addData.gmtEnd=date[1]._d.getTime();
    },
    // 团购商品
    groupProduct(value) {
      let va=value[value.length-1];
      // console.log(value);
      this.groupSh=va.slice(2);
      this.parameter.spuId=this.groupSh;
      this.skuDetial();
    },
    // 查询
    query(val){
      if(val){
        this.parameter.id=val
      }
      getList(Object.assign(this.parameter)).then(res => {
        console.log(res)
        this.data=res.data.items;
        this.pagination.total = res.data.total
      })
    },
    // 重置
    reset(){
      this.queryParam.id=null;
      this.query();
    },

    // 模态框
    showModal() {
      this.visible = true;
      this.CommodityTrees();
    },
    // 递归判断列表，解决最后一个children最后一项为空，设置成undefined
    getTreeData(data){
      for(var i=0;i<data.length;i++){
        if(data[i].children.length<1){
          // children若为空数组，则将children设为undefined
          data[i].children=undefined;
        }else {
          // children若不为空数组，则继续 递归调用 本方法
          this.getTreeData(data[i].children);
        }
      }
      return data;
    },

    // 获取商品分类树
    CommodityTrees(){
      getSpuBigTree(Object.assign(this.parameter)).then(res => {
        console.log(res)
        this.groupCommodity=this.getTreeData(res.data);
      })
    },
    handleOk(e) {

      if(this.addData['gmtStart']!==null && this.addData['gmtEnd']!==null && this.addData['spuId']!==null){
        this.visible = false;
        this.groupCommodity = null;
        this.createValue = [];
      } else{
        this.$message.error('请补入全信息！');
        return;
      }

      //向后台发起请求
      addGroupShopSpu(this.addData).then(res => {
        this.visible = false;
        this.query();
      })

      this.table=false;
    },
    handleCancel(e) {
      this.visible = false;
    },
  }
}
</script>
<style scoped>
  .flyray-btn{
    font-size:12px;padding:0 7px;margin:0 0 0 3px;height:24px;
  }
  .table-danger{
      color: #fff;
      background-color: #ff4d4f;
      border-color: #ff4d4f;
      margin-left: 5px;
  }
  .avatar-uploader > .ant-upload {
    width: 128px;
    height: 128px;
  }
  .ant-upload-select-picture-card i {
    font-size: 32px;
    color: #999;
  }

  .ant-upload-select-picture-card .ant-upload-text {
    margin-top: 8px;
    color: #666;
  }
  .commodityProperty,.commodityType{
    background-color: #fff;
    overflow: hidden;
    margin-bottom: 3px;
    box-shadow:#d4d4d4 0px 0px 3px;
  }
  .commodityProperty h1,.commodityType h1{
    font-size: 16px;
    margin:20px 0 0 15px;
    font-weight: bold;
  }
  .ant-modal-title{
    text-align: center;
    font-size: 18px;
  }
  .ant-form-item-label{
    text-align: left !important;
    padding-left: 6% !important;
  }
</style>

